package com.zhangzhan.gulimallmember.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Objects;

/**
 * @author 张一恒
 * @version 1.0
 * @description:
 * @date 2024/6/30 14:19
 */
@Configuration
public class MyRequestInterceptor {

    @Bean("requestInterceptor")
    public RequestInterceptor requestInterceptor() {
        return new RequestInterceptor() {

            @Override
            public void apply(RequestTemplate requestTemplate) {

                /**
                 *  Request targetRequest(RequestTemplate template) {
                 *         Iterator var2 = this.requestInterceptors.iterator();
                 *
                 *         while(var2.hasNext()) {
                 *             RequestInterceptor interceptor = (RequestInterceptor)var2.next();
                 *             interceptor.apply(template);
                 *         }
                 *
                 *         return this.target.apply(template);
                 *     }
                 */
                //实现 RequestInterceptor的apply方法，在远程调用时避免底层重新创建http客户端(RequestTemplate)丢失请求头的问题，在feign底层实现拦截器存入源服务的请求头

                /**
                 * 返回当前绑定到线程的 RequestAttributes。
                 * 返回值:当前绑定到线程的 RequestAttributes/ null
                 * 底层是threadLocal进行存储
                 */
                ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                if (!Objects.isNull(requestAttributes)) {
                    HttpServletRequest request = requestAttributes.getRequest();
                    String cookie = request.getHeader("Cookie"); //旧的请求头Cookie
                    //设置新客户端请求头
                    requestTemplate.header("Cookie", cookie);
                }

            }
        };
    }


}
